package com.aurora.leetcode.answer;



/**
 * @author Aurora
 * createTime 2022.11.05 22:27:06
 * @className addBinary_67.java
 */
public class addBinary_67 {
    /**
     * 给你两个二进制字符串 a 和 b ，以二进制字符串的形式返回它们的和。
     * */
    public String addBinary(String a, String b) {
        char[] charsA = a.toCharArray();
        char[] charsB = b.toCharArray();
        char[] charsC = charsB;
        int aLen = a.length() - 1;
        int bLen = b.length() - 1;
        if(aLen > bLen){
            charsC = charsA;
        }
        int i=aLen;
        int j=bLen;
        int cLen = i>=j?aLen:bLen;
        boolean plusOne = false;//是否需要进位
        for(; i>=0 && j>=0; --i,--j){
            if(charsA[i] == charsB[j]){
                switch (charsA[i]){
                    case '0':
                        charsC[cLen--]=plusOne == true?'1':'0';
                        plusOne = false;
                        break;
                    case '1':
                        charsC[cLen--] = plusOne == true?'1':'0';
                        plusOne = true;
                        break;
                }
            }else{
                if(plusOne){
                    charsC[cLen--] = '0';
                    plusOne = true;
                }else{
                    charsC[cLen--] = '1';
                    plusOne = false;
                }
            }
        }
        String c = "";
        while(plusOne){
            if(cLen >= 0 && charsC[cLen] == '1'){
                charsC[cLen--] = '0';
                plusOne = true;
            }else{
                if(cLen < 0){
                    c = "1";
                    break;
                }else{
                    charsC[cLen] = '1';
                    plusOne = false;
                }
            }
        }
        return c+new String(charsC);
    }
}
